package tenant_db

import (
	"context"
	"git.mycaigou.com/ycg/stark-extend/starkcommon"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"git.myscrm.cn/golang/stark/v4/config/setting"
)

// 获取租户db链接配置
func getTenantConfig(ctx context.Context, tenantCode string) (*TenantInstance, error) {
	var err error
	tenantConfig := TenantInstance{}
	err = stark.MySQLConn.Get(ctx).Table(tenantConfig.TableName()).Where("tenant_code = ?", tenantCode).First(&tenantConfig).Error
	if err != nil {
		return nil, err
	}
	return &tenantConfig, nil
}

// getTenantInfo 获取租户基本信息
func getTenantInfo(ctx context.Context, tenantCode string) (*Tenant, error) {
	var err error
	tenantPo := Tenant{}
	err = stark.MySQLConn.Get(ctx).Table(tenantPo.TableName()).Where("code = ?", tenantCode).Find(&tenantPo).Error
	if err != nil {
		return nil, err
	}
	return &tenantPo, nil
}

func getTenantMysqlConn(ctx context.Context, tenantCode string) (stark.MySQLConnIface, error) {
	if tenantCode == "" {
		return nil, ykerrcode.TogRPCError(TenantCodeEmpty, "租户 code 为空")
	}
	tenantConfig, err := getTenantConfig(ctx, tenantCode)
	if err != nil {
		return nil, err
	}
	// 获取租户mysql连接
	mysqlSetting := &setting.MysqlSettingS{
		Host:              setting.MysqlSetting.Host,
		UserName:          setting.MysqlSetting.UserName,
		Password:          setting.MysqlSetting.Password,
		DBName:            setting.MysqlSetting.DBName,
		Charset:           setting.MysqlSetting.Charset,
		MaxIdle:           setting.MysqlSetting.MaxIdle,
		MaxOpen:           setting.MysqlSetting.MaxOpen,
		Loc:               setting.MysqlSetting.Loc,
		ConnMaxLifeSecond: setting.MysqlSetting.ConnMaxLifeSecond,
		MultiStatements:   setting.MysqlSetting.MultiStatements,
		ParseTime:         setting.MysqlSetting.ParseTime,
		Timeout:           setting.MysqlSetting.Timeout,
	}

	// 目前是单实例，应该所有都在一个host里面
	if tenantConfig.Port != "" {
		mysqlSetting.Host = tenantConfig.Host + ":" + tenantConfig.Port
	} else {
		mysqlSetting.Host = tenantConfig.Host
	}

	mysqlSetting.DBName = tenantConfig.DbName
	mysqlSetting.UserName = tenantConfig.Username
	decryptPassWord, err := DecryptByAes(tenantConfig.Password) //对数据库密码进行AES解密
	if err != nil {
		return nil, ykerrcode.TogRPCError(TenantCodeDBPasswordErr, "租户数据库密码解密异常")
	}
	mysqlSetting.Password = decryptPassWord
	return starkcommon.NewMySQLConn(mysqlSetting)
}
